// 多语言支持
const translations = {
    'zh': {
        'page_title': '个人作品集',
        'site_logo': '我的作品集',
        'nav_home': '首页',
        'nav_about': '关于我',
        'nav_projects': '项目作品',
        'nav_contact': '联系我',
        'hero_greeting': '你好，我是',
        'hero_description': '专业从事UI/UX设计、网页开发和图形设计的创意工作者',
        'view_projects': '查看我的作品',
        'about_heading': '关于我',
        'about_para1': '大家好，我是一名专业的Python Developer，擅长消息中间件、实时数据处理和高可用架构设计。我对技术充满热情，不断追求创新和卓越。',
        'about_para2': '在业余时间，我喜欢学习Rust语言，同时也是动漫爱好者，特别喜欢《幸运星》、《孤独摇滚》和《摇曳露营》等作品。',
        'skills_heading': '专业技能',
        'skill_level_proficient': '精通',
        'skill_level_advanced': '熟练',
        'skill_level_beginner': '入门',
        'experience_heading': '专业经历',
        'timeline_2023_present': '2023年至今',
        'timeline_openai': 'OpenAI',
        'timeline_openai_desc': '高级Python开发者，负责大型语言模型的训练与优化，设计分布式训练系统架构',
        'timeline_2019_2023': '2019年-2023年',
        'timeline_google': 'Google',
        'timeline_google_desc': '软件工程师，参与开发搜索算法和数据处理管道，优化大规模数据检索性能',
        'timeline_2017_2019': '2017年-2019年',
        'timeline_stanford': '斯坦福大学',
        'timeline_stanford_desc': '计算机科学硕士，专注于分布式系统和人工智能研究',
        'timeline_2013_2017': '2013年-2017年',
        'timeline_tsinghua': '清华大学',
        'timeline_tsinghua_desc': '计算机科学与技术学士，主修软件工程和数据结构',
        'achievements_heading': '个人成就',
        'achievement1': '🏆 清华大学优秀毕业生',
        'achievement2': '🏆 微软MVP (Most Valuable Professional)',
        'achievement3': '🏆 华为开发者认证专家',
        'projects_heading': '项目作品',
        'project1_title': '项目名称1',
        'project1_desc': '项目简短描述，介绍项目的目标和成果。',
        'project2_title': '项目名称2',
        'project2_desc': '项目简短描述，介绍项目的目标和成果。',
        'project3_title': '项目名称3',
        'project3_desc': '项目简短描述，介绍项目的目标和成果。',
        'project4_title': '项目名称4',
        'project4_desc': '项目简短描述，介绍项目的目标和成果。',
        'view_details': '查看详情',
        'contact_heading': '联系我',
        'contact_description': '如果您对我的作品感兴趣，或者有任何合作机会，请随时与我联系。',
        'website_link': '个人网页',
        'email_link': '电子邮箱',
        'form_name': '您的姓名',
        'form_email': '电子邮箱',
        'form_message': '留言内容',
        'form_submit': '发送留言',
        'footer_text': '&copy; 2023 设计师姓名. 保留所有权利.',
        'form_placeholder_name': '请输入您的姓名',
        'form_placeholder_email': '请输入您的邮箱',
        'form_placeholder_message': '请输入您的留言',
        'alert_name': '请输入您的姓名',
        'alert_email': '请输入您的邮箱',
        'alert_email_invalid': '请输入有效的邮箱地址',
        'alert_message': '请输入您的留言内容',
        'alert_success': '感谢您的留言！我会尽快回复您。',
        'loading': '发送中...'
    },
    'en': {
        'page_title': 'Portfolio',
        'site_logo': 'My Portfolio',
        'nav_home': 'Home',
        'nav_about': 'About',
        'nav_projects': 'Projects',
        'nav_contact': 'Contact',
        'hero_greeting': 'Hello, I am',
        'hero_description': 'A creative professional specializing in UI/UX design, web development and graphic design',
        'view_projects': 'View My Works',
        'about_heading': 'About Me',
        'about_para1': 'Hello, I am a professional Python Developer, skilled in message middleware, real-time data processing, and high-availability architecture design. I am passionate about technology and constantly pursue innovation and excellence.',
        'about_para2': 'In my spare time, I enjoy learning Rust programming language and am also an anime enthusiast, particularly fond of works like "Lucky Star", "Bocchi the Rock!", and "Laid-Back Camp".',
        'skills_heading': 'Professional Skills',
        'skill_level_proficient': 'Proficient',
        'skill_level_advanced': 'Advanced',
        'skill_level_beginner': 'Beginner',
        'experience_heading': 'Professional Experience',
        'timeline_2023_present': '2023 - Present',
        'timeline_openai': 'OpenAI',
        'timeline_openai_desc': 'Senior Python Developer, responsible for training and optimizing large language models, designing distributed training system architecture',
        'timeline_2019_2023': '2019 - 2023',
        'timeline_google': 'Google',
        'timeline_google_desc': 'Software Engineer, participated in developing search algorithms and data processing pipelines, optimizing large-scale data retrieval performance',
        'timeline_2017_2019': '2017 - 2019',
        'timeline_stanford': 'Stanford University',
        'timeline_stanford_desc': 'Master of Computer Science, focused on distributed systems and artificial intelligence research',
        'timeline_2013_2017': '2013 - 2017',
        'timeline_tsinghua': 'Tsinghua University',
        'timeline_tsinghua_desc': 'Bachelor of Computer Science and Technology, majoring in software engineering and data structures',
        'achievements_heading': 'Achievements',
        'achievement1': '🏆 Outstanding Graduate of Tsinghua University',
        'achievement2': '🏆 Microsoft MVP (Most Valuable Professional)',
        'achievement3': '🏆 Huawei Developer Certification Expert',
        'projects_heading': 'Projects',
        'project1_title': 'Project Name 1',
        'project1_desc': 'Brief project description introducing the project goals and achievements.',
        'project2_title': 'Project Name 2',
        'project2_desc': 'Brief project description introducing the project goals and achievements.',
        'project3_title': 'Project Name 3',
        'project3_desc': 'Brief project description introducing the project goals and achievements.',
        'project4_title': 'Project Name 4',
        'project4_desc': 'Brief project description introducing the project goals and achievements.',
        'view_details': 'View Details',
        'contact_heading': 'Contact Me',
        'contact_description': 'If you are interested in my work or have any collaboration opportunities, please feel free to contact me.',
        'website_link': 'Personal Website',
        'email_link': 'Email',
        'form_name': 'Your Name',
        'form_email': 'Email Address',
        'form_message': 'Message',
        'form_submit': 'Send Message',
        'footer_text': '&copy; 2023 Designer Name. All rights reserved.',
        'form_placeholder_name': 'Please enter your name',
        'form_placeholder_email': 'Please enter your email',
        'form_placeholder_message': 'Please enter your message',
        'alert_name': 'Please enter your name',
        'alert_email': 'Please enter your email',
        'alert_email_invalid': 'Please enter a valid email address',
        'alert_message': 'Please enter your message content',
        'alert_success': 'Thank you for your message! I will reply to you as soon as possible.',
        'loading': 'Sending...'
    }
};

// 切换语言函数
function changeLanguage(language) {
    // 更新所有带有data-lang属性的元素
    document.querySelectorAll('[data-lang]').forEach(element => {
        const key = element.getAttribute('data-lang');
        if (translations[language][key]) {
            // 对于title标签，使用textContent而不是innerHTML
            if (element.tagName.toLowerCase() === 'title') {
                element.textContent = translations[language][key];
            } else {
                element.innerHTML = translations[language][key];
            }
        }
    });
    
    // 更新输入框占位符
    document.getElementById('name').placeholder = translations[language]['form_placeholder_name'];
    document.getElementById('email').placeholder = translations[language]['form_placeholder_email'];
    document.getElementById('message').placeholder = translations[language]['form_placeholder_message'];
    
    // 更新页面语言属性
    document.documentElement.lang = language === 'zh' ? 'zh-CN' : 'en-US';
    
    // 保存语言偏好到localStorage
    localStorage.setItem('preferredLanguage', language);
    
    // 更新语言按钮状态
    document.querySelectorAll('.lang-btn').forEach(btn => {
        if (btn.getAttribute('data-lang') === language) {
            btn.classList.add('active');
        } else {
            btn.classList.remove('active');
        }
    });
}

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 初始化语言
    // 优先使用localStorage中的偏好设置，否则根据浏览器语言判断
    const savedLanguage = localStorage.getItem('preferredLanguage');
    const browserLanguage = navigator.language || navigator.userLanguage;
    const initialLanguage = savedLanguage || (browserLanguage.includes('zh') ? 'zh' : 'en');
    changeLanguage(initialLanguage);
    
    // 语言切换按钮事件监听
    document.getElementById('lang-zh').addEventListener('click', function() {
        changeLanguage('zh');
    });
    
    document.getElementById('lang-en').addEventListener('click', function() {
        changeLanguage('en');
    });

    // 导航菜单交互
    const hamburger = document.querySelector('.hamburger');
    const navLinks = document.querySelector('.nav-links');
    const navItems = document.querySelectorAll('.nav-links li');

    // 汉堡菜单点击事件
    hamburger.addEventListener('click', function() {
        navLinks.classList.toggle('active');
        
        // 汉堡菜单动画
        hamburger.classList.toggle('toggle');
    });

    // 导航链接点击事件
    navItems.forEach(item => {
        item.addEventListener('click', function() {
            navLinks.classList.remove('active');
            hamburger.classList.remove('toggle');
        });
    });

    // 平滑滚动
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);
            
            if (targetElement) {
                window.scrollTo({
                    top: targetElement.offsetTop - 70, // 减去导航栏高度
                    behavior: 'smooth'
                });
            }
        });
    });

    // 联系表单提交事件
    const contactForm = document.getElementById('contactForm');
    
    if (contactForm) {
        contactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取当前语言
            const currentLang = document.documentElement.lang.includes('zh') ? 'zh' : 'en';
            
            // 获取表单数据
            const name = document.getElementById('name').value.trim();
            const email = document.getElementById('email').value.trim();
            const message = document.getElementById('message').value.trim();
            
            // 表单验证
            if (!name) {
                alert(translations[currentLang]['alert_name']);
                document.getElementById('name').focus();
                return;
            }
            
            // 邮箱格式验证
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!email) {
                alert(translations[currentLang]['alert_email']);
                document.getElementById('email').focus();
                return;
            } else if (!emailRegex.test(email)) {
                alert(translations[currentLang]['alert_email_invalid']);
                document.getElementById('email').focus();
                return;
            }
            
            if (!message) {
                alert(translations[currentLang]['alert_message']);
                document.getElementById('message').focus();
                return;
            }
            
            // 获取提交按钮并设置加载状态
            const submitButton = contactForm.querySelector('button[type="submit"]');
            const originalText = submitButton.innerHTML;
            submitButton.disabled = true;
            submitButton.innerHTML = translations[currentLang]['loading'];
            
            // 模拟表单提交延迟
            setTimeout(() => {
                // 在实际应用中，这里会发送表单数据到服务器
                console.log('表单数据:', { name, email, message });
                
                // 显示提交成功的提示
                alert(translations[currentLang]['alert_success']);
                
                // 重置表单
                contactForm.reset();
                
                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = originalText;
            }, 1000);
        });
    }
    
    // 表单输入交互增强
    const formInputs = document.querySelectorAll('.contact-form input, .contact-form textarea');
    formInputs.forEach(input => {
        // 输入框获取焦点效果
        input.addEventListener('focus', function() {
            this.parentElement.classList.add('focused');
        });
        
        // 输入框失去焦点效果
        input.addEventListener('blur', function() {
            this.parentElement.classList.remove('focused');
            
            // 如果输入框有内容，添加填充效果
            if (this.value.trim()) {
                this.parentElement.classList.add('filled');
            } else {
                this.parentElement.classList.remove('filled');
            }
        });
        
        // 初始检查是否有内容
        if (input.value.trim()) {
            this.parentElement.classList.add('filled');
        }
    });

    // 滚动显示动画
    const animateOnScroll = function() {
        const elements = document.querySelectorAll('.about, .projects, .contact');
        
        elements.forEach(element => {
            const elementPosition = element.getBoundingClientRect().top;
            const screenPosition = window.innerHeight / 1.3;
            
            if (elementPosition < screenPosition) {
                element.style.opacity = '1';
                element.style.transform = 'translateY(0)';
            }
        });
    };

    // 初始设置
    const sections = document.querySelectorAll('.about, .projects, .contact');
    sections.forEach(section => {
        section.style.opacity = '0';
        section.style.transform = 'translateY(50px)';
        section.style.transition = 'opacity 0.8s ease, transform 0.8s ease';
    });

    // 首次调用动画函数
    animateOnScroll();
    
    // 滚动时调用动画函数
    window.addEventListener('scroll', animateOnScroll);

    // 图片加载错误处理
    const images = document.querySelectorAll('img');
    images.forEach(img => {
        img.addEventListener('error', function() {
            // 替换为默认图片
            this.src = 'data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22200%22%20height%3D%22200%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20200%20200%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_15e8ba399e8%20text%20%7B%20fill%3Argba(200%2C200%2C200%2C.75)%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A10pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_15e8ba399e8%22%3E%3Crect%20width%3D%22200%22%20height%3D%22200%22%20fill%3D%22%23EEEEEE%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%2274%22%20y%3D%22104.5%22%3E图片加载失败%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E';
        });
    });

    // 窗口大小改变时的处理
    window.addEventListener('resize', function() {
        // 当窗口大小大于768px时，确保导航菜单是关闭的
        if (window.innerWidth > 768 && navLinks.classList.contains('active')) {
            navLinks.classList.remove('active');
            hamburger.classList.remove('toggle');
        }
    });
});

// 深色模式切换功能
function initTheme() {
    const themeToggle = document.getElementById('theme-toggle');
    const savedTheme = localStorage.getItem('theme') || 'light';
    
    // 设置初始主题
    if (savedTheme === 'dark') {
        document.documentElement.setAttribute('data-theme', 'dark');
        themeToggle.checked = true;
    }
    
    // 主题切换事件
    themeToggle.addEventListener('change', function() {
        if (this.checked) {
            document.documentElement.setAttribute('data-theme', 'dark');
            localStorage.setItem('theme', 'dark');
        } else {
            document.documentElement.setAttribute('data-theme', 'light');
            localStorage.setItem('theme', 'light');
        }
    });
}

// 在DOM加载完成后初始化主题
document.addEventListener('DOMContentLoaded', function() {
    // 初始化深色模式
    initTheme();
    
    // 初始化多语言（保持原有功能）
    const savedLang = localStorage.getItem('language') || 
                     (navigator.language.startsWith('zh') ? 'zh' : 'en');
    changeLanguage(savedLang);
    
    // 语言切换事件（保持原有功能）
    document.getElementById('lang-zh').addEventListener('click', () => changeLanguage('zh'));
    document.getElementById('lang-en').addEventListener('click', () => changeLanguage('en'));
    
    // 其他原有功能初始化...
});